import { db } from '../database/db';
import { GNews } from '../domain/g_news';

export const GNewsDao = {
    getNewsList: async function(offset = 0, limit = 10) {
        const baseQuery = db.selectFrom('g_news');
        const [{ count }] = await baseQuery.select(db.fn.countAll().as('count')).execute();
        const total = Number(count);
        if (total === 0) {
            return { list: [], total: 0 };
        }
        const list = await baseQuery
            .selectAll()
            .orderBy('sort', 'asc')
            .offset(offset)
            .limit(limit)
            .execute();
        return { list, total };
    },

    getNewsById: async function(id: number) {
        return await db.selectFrom('g_news')
            .selectAll()
            .where('id', '=', id)
            .executeTakeFirst();
    },

    getNewsByAlias: async function(alias: string) {
        return await db.selectFrom('g_news')
            .selectAll()
            .where('alias', '=', alias)
            .executeTakeFirst();
    },

    createNews: async function(data: GNews) {
        const result = await db.insertInto('g_news').values(data as any).executeTakeFirst();
        return Number((result as any).insertId);
    },

    updateNews: async function(id: number, data: Partial<GNews>) {
        const result = await db.updateTable('g_news')
            .set(data)
            .where('id', '=', id)
            .executeTakeFirst();
        return Number(result.numUpdatedRows);
    },

    deleteNews: async function(id: number) {
        // 物理删除，如需逻辑删除可自行扩展
        const result = await db.deleteFrom('g_news')
            .where('id', '=', id)
            .executeTakeFirst();
        return Number(result.numDeletedRows);
    },

    editNewsDesc: async function(data: any) {
        // 先根据lang和alias查询是否存在
        const result = await db.selectFrom('g_news_desc')
            .selectAll()
            .where('lang', '=', data.lang)
            .where('alias', '=', data.alias)
            .executeTakeFirst();
        console.log(result);
        if (result) {
            // 更新
            await db.updateTable('g_news_desc')
                .set(data)
                .where('lang', '=', data.lang)
                .where('alias', '=', data.alias)
                .executeTakeFirst();
        } else {
            // 插入
            await db.insertInto('g_news_desc').values(data).executeTakeFirst();
        }
    }
}


